//
//  skNetTools.m
//  FRQBluetoothKit_Example
//
//  Created by admin on 2023/10/31.
//  Copyright © 2023 xuchunhai. All rights reserved.
//

#import "skNetTools.h"

@implementation skNetTools
//获取当前时间戳
+(NSString *) getTimeNow{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;

        [formatter setDateStyle:NSDateFormatterMediumStyle];

        [formatter setTimeStyle:NSDateFormatterShortStyle];

        [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // 设置想要的格式，hh与HH的区别:分别表示12小时制,24小时制

        //设置时区,这一点对时间的处理很重要

        NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

        [formatter setTimeZone:timeZone];

        NSDate *dateNow = [NSDate date];

        NSString *timeStamp = [NSString stringWithFormat:@"%ld", (long)[dateNow timeIntervalSince1970]];
    return timeStamp;
}
+(NSString *)signString:(NSDictionary *)parameters timestamp:(NSString *)timestamp{
    
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:parameters];
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    [dic setValue:appVersion forKey:@"appVersion"];
    [dic setValue:@"ios" forKey:@"appType"];
    [dic setValue:timestamp forKey:@"timestamp"];
    
    NSArray *keyArray = [dic allKeys]; // 将dic中的全部key取出，并放到数组
    
    // 根据ASCII码,将参数key从小到大排序（升序）
    NSStringCompareOptions comparisonOptions =NSCaseInsensitiveSearch|NSNumericSearch|NSWidthInsensitiveSearch|NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1, NSString *obj2) {
        NSRange range = NSMakeRange(0, obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    NSArray *resultArr = [keyArray sortedArrayUsingComparator:sort];
        
    NSLog(@"字符串数组排序结果%@",resultArr);
    
    
    
    NSMutableString *singString=[[NSMutableString alloc] init];
    
    for (int i =0; i<resultArr.count; ++i) {
        NSString *key=[resultArr objectAtIndex:i];
        NSString *value=[dic objectForKey:key];
        NSString *str=[NSString stringWithFormat:@"%@=%@&",key,value];
        [singString appendString:str];
    }
    
    
    NSString *token=[NSString stringWithFormat:@"token=%@",KuserToken];
    
    NSString *key=@"e688769fcccc44cd3fd6f71ec570848e";
    
    [singString appendString:token];
    [singString appendString:key];
    
    NSString *temp = [singString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    NSLog(@"数据拼接%@",temp);
    
    NSString *result=[PKNetTools md5:temp];
    
    return result;
}
+(NSString *)signCysString:(NSDictionary *)parameters timestamp:(NSString *)timestamp{
    
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:parameters];
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    [dic setValue:appVersion forKey:@"appVersion"];
    [dic setValue:@"ios" forKey:@"appType"];
    [dic setValue:timestamp forKey:@"timestamp"];
    [dic setObject:KuserToken forKey:@"token"];
    
    NSArray *arr = [dic objectForKey:@"feedbackVoList"];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:0 error:nil];
    NSString  *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSMutableString *singString=[[NSMutableString alloc] init];
    
    [singString appendString:[NSString stringWithFormat:@"appType=%@&",@"ios"]];
    [singString appendString:[NSString stringWithFormat:@"appVersion=%@&",appVersion]];
    [singString appendString:[NSString stringWithFormat:@"feedbackVoList=%@&",jsonString]];
    [singString appendString:[NSString stringWithFormat:@"message=%@&",[dic objectForKey:@"message"]]];
    [singString appendString:[NSString stringWithFormat:@"timestamp=%@&",timestamp]];
    
    [singString appendString:[NSString stringWithFormat:@"token=%@",KuserToken]];
    
    [singString appendString:@"e688769fcccc44cd3fd6f71ec570848e"];
    
    NSString *temp = [singString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    NSLog(@"数据拼接%@",temp);
    
    NSString *result=[PKNetTools md5:temp];
    
    return result;
}
+ (void)skPOSTWithURL:(NSString *)url
         parameters:(NSDictionary *)parameters
        cachePolicy:(HJCachePolicy)cachePolicy
           callback:(HJHttpRequest)callback
{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:parameters];
    
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    [dic setObject:appVersion forKey:@"appVersion"];
    [dic setObject:@"ios" forKey:@"appType"];
    NSString *timeStamp=[self getTimeNow];
    [dic setObject:timeStamp forKey:@"timestamp"];
    
    NSString *sign=[skNetTools signString:parameters timestamp:timeStamp];
    
    [dic setObject:sign forKey:@"sign"];
    
    [PKNetTools POSTWithHeaderURL:url parameters:dic cachePolicy:cachePolicy callback:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        skNetModel *data=[skNetModel mj_objectWithKeyValues:responseObject];
        callback(data,error);
    }];
}

+(void)skGETWithURL:(NSString *)url
         parameters:(NSDictionary *)parameters
        cachePolicy:(HJCachePolicy)cachePolicy
           callback:(HJHttpRequest)callback{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:parameters];
    
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    [dic setObject:appVersion forKey:@"appVersion"];
    [dic setObject:@"ios" forKey:@"appType"];
    NSString *timeStamp=[self getTimeNow];
    [dic setObject:timeStamp forKey:@"timestamp"];
    
    NSString *sign=[skNetTools signString:parameters timestamp:timeStamp];
    
    [dic setObject:sign forKey:@"sign"];
    
    [PKNetTools GETWithHeaderURL:url parameters:dic cachePolicy:cachePolicy callback:callback];
}

+(NSInteger)skgetUserType{
    return [[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] integerValue];
//    return 1;
}
+(void)sksetUserType:(NSString *)type{
    [[NSUserDefaults standardUserDefaults] setObject:type forKey:@"userType"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
+(NSString *)skgetToken{
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    if (token.length==0) {
        token=@"";
    }
    return token;
}
+(void)sksetToken:(NSString *)token{
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
+(NSString *)skgetMyDevice{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"myDevice"];
}
+(void)sksetMyDevice:(NSDictionary *)token{
    if(![token isKindOfClass:[NSNull class]]){
        NSString *uuid=[NSString stringWithFormat:@"%@",[token objectForKey:@"uuid"]];
        
        [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:@"myDevice"];
        
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}
+(Boolean)isMyDeviceNull{
    NSString *dic=[self skgetMyDevice];
    if(dic.length>0){
        return YES;
    }else{
        return NO;
    }
}
+ (void)getBody:(NSDictionary *)params andUrl:(NSString *)url callback:(nonnull HJHttpRequest)callback{
    
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:params];
    
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    [dic setObject:appVersion forKey:@"appVersion"];
    [dic setObject:@"ios" forKey:@"appType"];
    NSString *timeStamp=[self getTimeNow];
    [dic setObject:timeStamp forKey:@"timestamp"];
    
    
    NSString *sign=[skNetTools signCysString:params timestamp:timeStamp];
    
    [dic setObject:sign forKey:@"sign"];
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];;
       
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    //设置超时时长
    request.timeoutInterval = 30.0;
    //设置token
    [request setValue:KuserToken forHTTPHeaderField:@"token"];
    
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    //将对象设置到requestbody中 ,主要是这步操作
    [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    //进行网络请求
    [[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
    
        if (!error) {
            NSDictionary *dict;
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                dict = (NSDictionary *)responseObject;
            }else{
                dict = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            }
            callback(dict,error);
        } else {
            NSLog(@"----error.userInfo----%@", error.userInfo);
        }
    }] resume];
}
@end
